package com.thread.threadpool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author: mayu
 * @date: 2021年04月16日 16:44
 * 使用FixedThreadPool来并行处理任务
 */
public class TestFixedThreadPool {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        getPrime(1, 20000000);
        long end = System.currentTimeMillis();
        System.out.println("单线程执行所花时间为：" + (end - start));

        int cpuCoreNum = 4;
        ExecutorService es = Executors.newFixedThreadPool(cpuCoreNum);
        Future<List<Integer>> f1 = es.submit(new MyTask(1, 5000000));
        Future<List<Integer>> f2 = es.submit(new MyTask(5000001, 10000000));
        Future<List<Integer>> f3 = es.submit(new MyTask(10000001, 15000000));
        Future<List<Integer>> f4 = es.submit(new MyTask(15000001, 20000000));

        start = System.currentTimeMillis();
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        end = System.currentTimeMillis();
        System.out.println("线程池执行所花时间为：" + (end - start));

    }

    static class MyTask implements Callable<List<Integer>> {
        private Integer start;
        private Integer end;

        public MyTask(Integer start, Integer end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public List<Integer> call() throws Exception {
            return getPrime(start, end);
        }
    }

    static Boolean isPrime(Integer num) {
        if (num % 2 == 0) {
            return false;
        }
        return true;
    }

    static List<Integer> getPrime(Integer start, Integer end) {
        List<Integer> lists = new ArrayList<>();
        for (int i = start; i < end; i++) {
            if (isPrime(i)) {
                lists.add(i);
            }
        }
        return lists;
    }
}
